<?php
defined('BASEPATH') OR exit('No direct script access allowed');

require APPPATH . '/libraries/REST_Controller.php';
/**
 * Created by fish.
 * Date: 2017/6/11
 * Time: 下午5:41
 */
class Supply extends REST_Controller{

    public function __construct(){
        parent::__construct();
    }

    private function response_code($total_num = 0, $list = array(), $message = '请求成功',$code = 200001){
        return [
            'code' => $code,
            'message' => $message,
            'data' => [
                'total_num' => $total_num,
                'list' => $list
            ]
        ];
    }
    /**
     * 获取区域经理的供货列表
     */
    public function supply_list_get(){
        $mid = parent::get('mid')?parent::get('mid'):0;
        $deliverDate = parent::get('deliverDate')?parent::get('deliverDate'):'';
        $begainDate = parent::get('begainDate')?parent::get('begainDate'):'';
        $endDate = parent::get('endDate')?parent::get('endDate'):'';
        $type = parent::get('type')?parent::get('type'):'';
        $status = parent::get('status')?parent::get('status'):'0';

        $tmpMid = [];
        $productList = [];
        if(!empty($mid)){
            $this->load->model('Manager_model');
            $isAll = false;
            if(count($mid) == 1 && $mid[0] == 0){
                $isAll = true;
                $mid = [];
            }else{
                foreach($mid as $key => $value) {
                    $managerInfo = $this->Manager_model->getManagerDetail($value);
                    $tmpMid[$key]['name'] = $managerInfo['realname'];
                    $tmpMid[$key]['id'] = $value;
                }
                $mid = $tmpMid;
                unset($tmpMid);
            }
            $this->load->model('Supply_model');
            $productList = $this->Supply_model->getSupplyList($mid, $begainDate, $endDate, $deliverDate, $status, $isAll);
        }
        if($type == 'export'){
            $this->supply_list_export($productList, $begainDate, $endDate, $deliverDate);
        }else {
            $data = $this->response_code(count($productList), $productList);
            $this->response($data, REST_Controller::HTTP_OK);
        }
    }

    /**
     * 导出供货列表
     * @param $productList
     * @param $begainDate
     * @param $endDate
     * @param $deliverDate
     */
    public function supply_list_export($productList, $begainDate, $endDate, $deliverDate){
        error_reporting(E_ALL);
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/IOFactory', 'IOFactory');
        $objPHPExcel = new PHPExcel();

        $excelTitle = '供货统计('.$begainDate .'-'.$endDate.')';
        $tableHead = array(
            array(
                "product_id" => "编号",
                "category_name" => "分类",
                "pname" => "名称",
                "sku_name" => "规格",
                "product_num" => "数量",
                "precise_unit" => "单位",
                "status" => "状态"
            )
        );

        $tableColumn = array('A','B','C','D','E','F');

        $totalData = [];
        $sheetNum = count($productList);
        foreach($productList as $key => $value){
            //设置当前sheet名称
            $sheetTitle = $value[1];
            $objPHPExcel->createSheet();
            $objPHPExcel->setActiveSheetIndex($key);
            $objPHPExcel->getActiveSheet()->setTitle($sheetTitle);

            //表格单元格水平居中
            $objPHPExcel->getActiveSheet()->getStyle($tableColumn[0].':'.$tableColumn[5])->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

            //表格单元格宽度设置
            /*for($i = 0; $i < 5; $i++){
                //$objPHPExcel->getActiveSheet()->getColumnDimension($tableColumn[$i])->setAutoSize(true);
                $objPHPExcel->getActiveSheet()->getColumnDimension($tableColumn[$i])->setWidth(12);
            }*/

            $data = $value[0];
            $newData = array_merge($tableHead, $data);
            /*合并单元格 —— 配送负责人栏(订单日期&配送日期) begain*/
            $objPHPExcel->getActiveSheet()->mergeCells($tableColumn[0].'1:'.$tableColumn[5].'1');
            $objPHPExcel->getactivesheet()->setcellvalue($tableColumn[0].'1', $sheetTitle.' '.$begainDate .' - '.$endDate.' 配送日期：' . $deliverDate);
            /*合并单元格 —— 配送负责人栏(订单日期&配送日期) end*/

            /*填充单元格数据 begain*/
            foreach($newData as $k => $v){
                /*switch ($v['status']){
                    case '0':
                        $status = '已确认';
                        break;
                    case '1':
                        $status = '已完成';
                        break;
                    case '2':
                        $status = '已配货';
                        break;
                    case '3':
                        $status = '已取消';
                        break;
                    case '4':
                        $status = '待付款';
                        break;
                    case '9':
                        $status = '待付款';
                        break;
                    default:
                        $status = '状态';
                        break;
                }*/
                $objPHPExcel->getactivesheet()->setcellvalue($tableColumn[0].($k+2), $v['product_id']);
                $objPHPExcel->getactivesheet()->setcellvalue($tableColumn[1].($k+2), $v['category_name']);
                $objPHPExcel->getactivesheet()->setcellvalue($tableColumn[2].($k+2), $v['pname']);
                $objPHPExcel->getactivesheet()->setcellvalue($tableColumn[3].($k+2), $v['sku_name']);
                $objPHPExcel->getactivesheet()->setcellvalue($tableColumn[4].($k+2), $v['product_num']);
                $objPHPExcel->getactivesheet()->setcellvalue($tableColumn[5].($k+2), $v['precise_unit']);
//                $objPHPExcel->getactivesheet()->setcellvalue($tableColumn[6].($k+2), $status);
                if($k != 0){
                    $totalData[] = $v;
                }
            }
            /*填充单元格数据 end*/
        }

        /*表格汇总sheet begain*/
        /*$newTotalData = array_merge($tableHead, $totalData);
        $objPHPExcel->setActiveSheetIndex($sheetNum);
        $objPHPExcel->getActiveSheet()->setTitle('所有清单');
        $objPHPExcel->getActiveSheet()->getStyle($tableColumn[0].':'.$tableColumn[5])->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        /*合并单元格 —— 订单日期&配送日期 begain*/
        /*$objPHPExcel->getActiveSheet()->mergeCells($tableColumn[0].'1:'.$tableColumn[5].'1');
        $objPHPExcel->getactivesheet()->setcellvalue($tableColumn[0].'1', '订单日期：'.$begainDate .' - '.$endDate.' 配送日期：' . $deliverDate);*/
        /*合并单元格 —— 订单日期&配送日期 end*/
        /*foreach($newTotalData as $k => $v){
            $objPHPExcel->getactivesheet()->setcellvalue($tableColumn[0].($k+2), $v['product_id']);
            $objPHPExcel->getactivesheet()->setcellvalue($tableColumn[1].($k+2), $v['category_name']);
            $objPHPExcel->getactivesheet()->setcellvalue($tableColumn[2].($k+2), $v['pname']);
            $objPHPExcel->getactivesheet()->setcellvalue($tableColumn[3].($k+2), $v['sku_name']);
            $objPHPExcel->getactivesheet()->setcellvalue($tableColumn[4].($k+2), $v['product_num']);
            $objPHPExcel->getactivesheet()->setcellvalue($tableColumn[5].($k+2), $v['precise_unit']);
            //单元格颜色填充
            /*if($k % 2 == 0){
                $objPHPExcel->getActiveSheet()->getStyle('D13')->getBorders()->getLeft()->getColor()->setARGB('FF993300');
                $objPHPExcel->getActiveSheet()->getStyle($tableColumn[0].($k+1).":".$tableColumn[4].($k+1))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
                $objPHPExcel->getActiveSheet()->getStyle($tableColumn[0].($k+1).":".$tableColumn[4].($k+1))->getFill()->getStartColor()->setRGB('ACACAC');
            }*/

        /*}*/
        /*表格汇总sheet end*/

        header('Content-Type: application/vnd.ms-excel; charset=utf-8');
        header("Content-Disposition: attachment;filename=".$excelTitle.".xls");
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;

    }

    /**
     * 显示需要度量的商品信息 @方龙喜
     * @param $categoryID string
     */
    public function product_measure_get(){
        $productList = [];
        $cid = parent::get('cid')?parent::get('cid'):'';
        $type = parent::get('type')?parent::get('type'):'';
        $categoryID = explode(',', $cid);
        if(count($categoryID) > 0 ){
            $this->load->model('product_model');
            $productIdsCategory = $this->product_model->getProductIdForCategory($categoryID);
            if(!empty($productIdsCategory)){
                $where['order_by'] = 'first_cat_id asc, second_cat_id asc, id asc';
                $where['where'] = 'shelf = 1';
                $where['where_in'] = array('id' => $productIdsCategory);
                $productList = $this->product_model->getProductList($where);
                foreach($productList['products'] as $key => $value){
                    $tmpSku = $this->product_model->getProductGoods($key);
                    $productList['products'][$key]['goodsList'] = $tmpSku;
                }
            }
        }
        if($type == 'export'){
            $this->measure_list_export($productList['products']);
        }else {
            $data = $this->response_code($productList['productNum'], $productList['products']);
            $this->response($data, REST_Controller::HTTP_OK);
        }
    }

    /**
     * 导出度量商品
     * @param $productList
     * @param $begainDate
     * @param $endDate
     * @param $deliverDate
     */
    public function measure_list_export($productList){
        error_reporting(E_ALL);
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/IOFactory', 'IOFactory');
        $objPHPExcel = new PHPExcel();

        $excelTitle = '度量统计('.date("Y-m-d").')';
        $tableHead = array(
            array(
                "first_cat_name" => "一级分类",
                "second_cat_name" => "二级分类",
                "product_name" => "名称",
                "sku_name" => "规格",
                "precise_unit" => "单位",
                "sell_price" => "价格"
            )
        );

        $tableColumn = array('A','B','C','D','E','F');

        $tmpProductList = [];
        foreach($productList as $key => $value){
            $tmpProductList[] = $value;
        }
        $productList = $tmpProductList;
        unset($tmpProductList);

        $newProductList = [];
        foreach($productList as $key => $value){
            foreach($value['goodsList'] as $k => $v){
                if($v['shelf'] == 1){
                    $newProductList[$key.'-'.$k]['first_cat_name'] = $value['category'][0]['category_name'];
                    $newProductList[$key.'-'.$k]['second_cat_name'] = $value['category'][1]['category_name'];
                    $newProductList[$key.'-'.$k]['product_name'] = $v['product_name'];
                    if(!empty($v['spec_array'])){
                        $newProductList[$key.'-'.$k]['sku_name'] = $v['spec_array'][0]['value'];
                    }else{
                        $newProductList[$key.'-'.$k]['sku_name'] = '无规格';
                    }
                    $newProductList[$key.'-'.$k]['precise_unit'] = $v['precise_unit'];
                    $newProductList[$key.'-'.$k]['sell_price'] = $v['sell_price'];
                }
            }
        }

        $totalData = [];

        //设置当前sheet名称
        $sheetTitle = 'worksheet';
        $objPHPExcel->createSheet();
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle($sheetTitle);

        //表格单元格水平居中
        $objPHPExcel->getActiveSheet()->getStyle($tableColumn[0].':'.$tableColumn[5])->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

        $newData = array_merge($tableHead, $newProductList);

        $tmpNewData = [];
        foreach($newData as $key => $value){
            $tmpNewData[] = $value;
        }
        $newData = $tmpNewData;
        unset($tmpNewData);

        /*填充单元格数据 begain*/
        foreach($newData as $k => $v){
            $objPHPExcel->getactivesheet()->setcellvalue($tableColumn[0].($k+1), $v['first_cat_name']);
            $objPHPExcel->getactivesheet()->setcellvalue($tableColumn[1].($k+1), $v['second_cat_name']);
            $objPHPExcel->getactivesheet()->setcellvalue($tableColumn[2].($k+1), $v['product_name']);
            $objPHPExcel->getactivesheet()->setcellvalue($tableColumn[3].($k+1), $v['sku_name']);
            $objPHPExcel->getactivesheet()->setcellvalue($tableColumn[4].($k+1), $v['precise_unit']);
            $objPHPExcel->getactivesheet()->setcellvalue($tableColumn[5].($k+1), $v['sell_price']);
            if($k != 0){
                $totalData[] = $v;
            }
        }
        /*填充单元格数据 end*/

        header('Content-Type: application/vnd.ms-excel; charset=utf-8');
        header("Content-Disposition: attachment;filename=".$excelTitle.".xls");
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;

    }
}